package com.wangxiaoxuan.seckill.rabbitmq;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:消息发送者
 * @Author：wangxiaoxuan
 * @Date
 **/
@Service
@Slf4j
public class MQSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送将order存入mysql的消息
     * @param order 订单信息
     * @param seckillOrder 秒杀订单信息，但其中的订单id未添加
     */
    public void sendOrder(String order,String seckillOrder){
        HashMap<String,String> map = new HashMap<>();
        map.put("order",order);
        map.put("seckillOrder",seckillOrder);
        rabbitTemplate.convertAndSend("exchange_seckill","seckill.order.1",map);
    }

    /**
     * 当秒杀商品库存为0，将缓存中库存写入数据库
     * @param goodsId
     */
    public void sendDecreaseStock(String goodsId){
        rabbitTemplate.convertAndSend("exchange_seckill","seckill.stock.2",goodsId);
    }

    /**
     * 将订单号发给延时队列，并且设置时间，时间到达之后，如果订单未支付，则取消订单
     */
    public void sendOrderDelay(String orderKey){
        rabbitTemplate.convertAndSend("queue_seckill_delay", (Object) orderKey, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("300000");
                return message;
            }
        });
    }

    /**
     * 支付之后，同步数据
     * @param map
     */
    public void sendPay(Map<String,String> map){
        rabbitTemplate.convertAndSend("queue_seckill_pay",map);
    }
}
